package chapter8.eg10.netty;

import chapter8.eg10.SubscribeReqProto;
import chapter8.eg10.SubscribeRespProto;
import chapter8.eg10.SubscribeRespProto.SubscribeResp;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import java.util.ArrayList;
import java.util.List;

public class SubReqClientHandler extends SimpleChannelInboundHandler<SubscribeRespProto.SubscribeResp> {

  @Override
  public void channelActive(ChannelHandlerContext ctx) throws Exception {
    for (int i = 0; i < 10; i++) {
      ctx.write(subReq(i));
    }

    ctx.flush();
  }

  private SubscribeReqProto.SubscribeReq subReq(int i) {
    List<String> address = new ArrayList<>();
    address.add("NanJing YuHuaTai");
    address.add("BeiJing LiuLiChang");
    address.add("ShenZhen HongShuLin");

    SubscribeReqProto.SubscribeReq.Builder builder =
      SubscribeReqProto.SubscribeReq.newBuilder()
        .setSubReqID(i)
        .setUserName("Lilinfeng")
        .setProductName("Netty Book For Protobuf")
        .addAllAddress(address);
    return builder.build();
  }

  @Override
  protected void channelRead0(ChannelHandlerContext ctx, SubscribeResp msg) throws Exception {
    System.out.println("Receive server response: [" + msg + "]");
  }

  @Override
  public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
    ctx.flush();
  }

  @Override
  public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    cause.printStackTrace();
    ctx.close();
  }
}
